import React, { useState } from 'react';
import { DragDropContext, Droppable, Draggable, DropResult } from 'react-beautiful-dnd';
import { Card, Button, Input, DatePicker, TimePicker, Form, Modal, Space, Typography, Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { TravelPlan, TravelDay, TravelActivity } from '../types';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

interface TravelPlannerProps {
  initialPlan?: TravelPlan;
  onSave?: (plan: TravelPlan) => void;
}

const TravelPlanner: React.FC<TravelPlannerProps> = ({ initialPlan, onSave }) => {
  const [plan, setPlan] = useState<TravelPlan>(
    initialPlan || {
      id: Date.now().toString(),
      title: '我的旅行计划',
      destination: '',
      startDate: '',
      endDate: '',
      days: []
    }
  );
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingDay, setEditingDay] = useState<string | null>(null);
  const [activityForm] = Form.useForm();

  const handleDragEnd = (result: DropResult) => {
    if (!result.destination) return;

    const { source, destination } = result;
    
    if (source.droppableId === destination.droppableId) {
      // 同一天内重新排序
      const dayIndex = plan.days.findIndex(d => d.id === source.droppableId);
      const newDays = [...plan.days];
      const activities = [...newDays[dayIndex].activities];
      const [removed] = activities.splice(source.index, 1);
      activities.splice(destination.index, 0, removed);
      newDays[dayIndex].activities = activities;
      setPlan({ ...plan, days: newDays });
    }
  };

  const addActivity = (dayId: string, values: any) => {
    const newActivity: TravelActivity = {
      id: Date.now().toString(),
      title: values.title,
      description: values.description,
      time: values.time.format('HH:mm'),
      location: values.location,
      duration: values.duration
    };

    const newDays = plan.days.map(day => {
      if (day.id === dayId) {
        return {
          ...day,
          activities: [...day.activities, newActivity]
        };
      }
      return day;
    });

    setPlan({ ...plan, days: newDays });
    setIsModalVisible(false);
    activityForm.resetFields();
  };

  const deleteActivity = (dayId: string, activityId: string) => {
    const newDays = plan.days.map(day => {
      if (day.id === dayId) {
        return {
          ...day,
          activities: day.activities.filter(a => a.id !== activityId)
        };
      }
      return day;
    });
    setPlan({ ...plan, days: newDays });
  };

  const generateDays = (dates: any) => {
    if (!dates) return;
    
    const startDate = dates[0];
    const endDate = dates[1];
    const days: TravelDay[] = [];
    
    let currentDate = startDate;
    let dayIndex = 1;
    
    while (currentDate.isSameOrBefore(endDate, 'day')) {
      days.push({
        id: `day-${dayIndex}`,
        date: currentDate.format('YYYY-MM-DD'),
        activities: []
      });
      currentDate = currentDate.add(1, 'day');
      dayIndex++;
    }
    
    setPlan({
      ...plan,
      startDate: startDate.format('YYYY-MM-DD'),
      endDate: endDate.format('YYYY-MM-DD'),
      days
    });
  };

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Title level={4}>旅行计划设置</Title>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Input
            placeholder="计划标题"
            value={plan.title}
            onChange={(e) => setPlan({ ...plan, title: e.target.value })}
          />
          <Input
            placeholder="目的地"
            value={plan.destination}
            onChange={(e) => setPlan({ ...plan, destination: e.target.value })}
          />
          <RangePicker
            onChange={generateDays}
            style={{ width: '100%' }}
          />
        </Space>
      </Card>

      <DragDropContext onDragEnd={handleDragEnd}>
        {plan.days.map((day) => (
          <Card key={day.id} style={{ marginBottom: 16 }}>
            <Title level={4}>
              第{plan.days.indexOf(day) + 1}天 - {dayjs(day.date).format('MM月DD日')}
            </Title>
            
            <Droppable droppableId={day.id}>
              {(provided) => (
                <div {...provided.droppableProps} ref={provided.innerRef}>
                  {day.activities.map((activity, index) => (
                    <Draggable key={activity.id} draggableId={activity.id} index={index}>
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                          style={{
                            ...provided.draggableProps.style,
                            marginBottom: 8,
                            padding: 12,
                            backgroundColor: snapshot.isDragging ? '#f0f0f0' : '#fafafa',
                            border: '1px solid #d9d9d9',
                            borderRadius: 6
                          }}
                        >
                          <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                            <div>
                              <Text strong>{activity.title}</Text>
                              <br />
                              <Text type="secondary" style={{ fontSize: 12 }}>
                                <ClockCircleOutlined /> {activity.time} | {activity.location}
                              </Text>
                              <br />
                              <Text style={{ fontSize: 12 }}>{activity.description}</Text>
                            </div>
                            <Button
                              type="text"
                              icon={<DeleteOutlined />}
                              onClick={() => deleteActivity(day.id, activity.id)}
                            />
                          </Space>
                        </div>
                      )}
                    </Draggable>
                  ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>

            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingDay(day.id);
                setIsModalVisible(true);
              }}
              style={{ width: '100%', marginTop: 8 }}
            >
              添加活动
            </Button>
          </Card>
        ))}
      </DragDropContext>

      <Modal
        title="添加活动"
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          activityForm.resetFields();
        }}
        onOk={() => {
          activityForm.validateFields().then(values => {
            if (editingDay) {
              addActivity(editingDay, values);
            }
          });
        }}
      >
        <Form form={activityForm} layout="vertical">
          <Form.Item name="title" label="活动名称" rules={[{ required: true }]}>
            <Input placeholder="例如：参观故宫" />
          </Form.Item>
          <Form.Item name="description" label="活动描述">
            <Input.TextArea placeholder="活动详细描述" />
          </Form.Item>
          <Form.Item name="time" label="开始时间" rules={[{ required: true }]}>
            <TimePicker format="HH:mm" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="location" label="地点" rules={[{ required: true }]}>
            <Input placeholder="例如：故宫博物院" />
          </Form.Item>
          <Form.Item name="duration" label="持续时间（分钟）" rules={[{ required: true }]}>
            <Input type="number" placeholder="例如：120" />
          </Form.Item>
        </Form>
      </Modal>

      <Button
        type="primary"
        onClick={() => onSave?.(plan)}
        style={{ width: '100%' }}
      >
        保存计划
      </Button>
    </div>
  );
};

export default TravelPlanner;
